from flask import Flask, render_template, request, jsonify
import json
import os
from datetime import datetime
import uuid
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
sys.stderr = codecs.getwriter("utf-8")(sys.stderr.detach())
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

app = Flask(__name__)

# 数据文件路径
DATA_FILE = 'events.txt'


# 确保数据文件存在
def init_data_file():
    if not os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            f.write('')  # 创建空文件


# 读取所有事件
def read_events():
    events = []
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                for line in f:
                    if line.strip():
                        event = json.loads(line.strip())
                        # 如果事件没有ID，则添加一个
                        if 'id' not in event:
                            event['id'] = str(uuid.uuid4())
                        events.append(event)
        except Exception as e:
            print(f"读取文件时出错: {e}")
    return events


# 写入所有事件到文件（覆盖写入）
def write_all_events_to_file(events):
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            for event in events:
                f.write(json.dumps(event, ensure_ascii=False) + '\n')
        return True
    except Exception as e:
        print(f"写入文件时出错: {e}")
        return False


# 写入单个事件到文件（追加）
def write_event_to_file(event):
    try:
        with open(DATA_FILE, 'a', encoding='utf-8') as f:
            f.write(json.dumps(event, ensure_ascii=False) + '\n')
        return True
    except Exception as e:
        print(f"写入文件时出错: {e}")
        return False


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/get_events')
def get_events():
    try:
        events = read_events()
        return jsonify({'success': True, 'events': events})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})


@app.route('/save_event', methods=['POST'])
def save_event():
    try:
        # 获取JSON数据
        data = request.get_json()

        # 验证必要字段
        if not all(key in data for key in ['datetime', 'person', 'description']):
            return jsonify({'success': False, 'message': '缺少必要字段'})

        # 创建事件对象，添加唯一ID
        event = {
            'id': str(uuid.uuid4()),
            'datetime': data['datetime'],
            'person': data['person'],
            'description': data['description'],
            'recorded_at': datetime.now().isoformat()
        }

        # 保存到文件
        if write_event_to_file(event):
            return jsonify({'success': True, 'message': '事件已保存到文件', 'event': event})
        else:
            return jsonify({'success': False, 'message': '保存文件时出错'})

    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})


@app.route('/update_event', methods=['POST'])
def update_event():
    try:
        # 获取JSON数据
        data = request.get_json()

        # 验证必要字段
        if not all(key in data for key in ['id', 'datetime', 'person', 'description']):
            return jsonify({'success': False, 'message': '缺少必要字段'})

        # 读取所有事件
        events = read_events()

        # 查找并更新事件
        event_found = False
        for i, event in enumerate(events):
            if event['id'] == data['id']:
                events[i] = {
                    'id': data['id'],
                    'datetime': data['datetime'],
                    'person': data['person'],
                    'description': data['description'],
                    'recorded_at': event.get('recorded_at', datetime.now().isoformat())
                }
                event_found = True
                break

        if not event_found:
            return jsonify({'success': False, 'message': '未找到指定事件'})

        # 重新写入所有事件
        if write_all_events_to_file(events):
            return jsonify({'success': True, 'message': '事件已更新'})
        else:
            return jsonify({'success': False, 'message': '更新文件时出错'})

    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})


@app.route('/delete_event', methods=['POST'])
def delete_event():
    try:
        # 获取JSON数据
        data = request.get_json()

        # 验证必要字段
        if 'id' not in data:
            return jsonify({'success': False, 'message': '缺少事件ID'})

        # 读取所有事件
        events = read_events()

        # 过滤掉要删除的事件
        original_length = len(events)
        events = [event for event in events if event['id'] != data['id']]

        if len(events) == original_length:
            return jsonify({'success': False, 'message': '未找到指定事件'})

        # 重新写入所有事件
        if write_all_events_to_file(events):
            return jsonify({'success': True, 'message': '事件已删除'})
        else:
            return jsonify({'success': False, 'message': '更新文件时出错'})

    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})


if __name__ == '__main__':
    init_data_file()
    app.run(debug=True, host='0.0.0.0', port=5005)
